package com.android.basewars;


import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

public class AttackLogActivity extends Activity {
	
	protected JSONArray results;
	int userID;
	ListView lv;
	protected String[] ownBases;
	protected JSONArray ownBasesresult;
	protected JSONArray Baseresult;
	public String lastBaseName = "";
	
	
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.attacklogview);
		
		getOwnBases();
		
		lv = (ListView)findViewById(R.id.listView2);
		
		Bundle extras = getIntent().getExtras();
	    if(extras !=null)
	    {
	    	userID = extras.getInt("userid"); 
	    	getAttackLogs();
	    }
	    
		
	}
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
	    MenuInflater inflater = getMenuInflater();
	    inflater.inflate(R.menu.menu, menu);
	    return true;
	}
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
	    // Handle item selection
	    switch (item.getItemId()) {
	    case R.id.map:
	    	Intent m = new Intent(getApplicationContext(), BaseWarsActivity.class);
	 		m.putExtra("userid", userID);
	 		startActivity(m);
	 		finish();
	        return true;
	    case R.id.rankinglist:
	    	Intent rl = new Intent(getApplicationContext(), RankingActivity.class);
	 		rl.putExtra("userid", userID);
	 		startActivity(rl);
	 		finish();
	        return true;
	    case R.id.attacklog:
//	    	Intent al = new Intent(getApplicationContext(), AttackLogActivity.class);
//	 		al.putExtra("userid", userID);
//	 		startActivity(al);
//	 		finish();
	        return true;
	    case R.id.editaccount:
	    	Intent e = new Intent(getApplicationContext(), EditAccountActivity.class);
	 		e.putExtra("userid", userID);
	 		startActivity(e);
	 		finish();
	        return true;  
	    default:
	        return super.onOptionsItemSelected(item);
	    }
	}
	private void setListViewAdapter() {
		  ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
	        HashMap<String, String> map;
			for(int i=0;i <results.length();i++){
				JSONObject o;
				try {
					o = results.getJSONObject(i);
					
					String atk_id =  o.getString("attacking_base_id");
				 	String def_id = o.getString("defending_base_id");
				 	String winning = o.getString("won");
				 	String tijd = o.getString("timestamp");
				 	
				 	String status = "";
				 	for(int j=0; j < ownBasesresult.length(); j++){
				 		if(ownBases[j].equals(atk_id)){
				 			 status = "";
						 	if(winning.equals("1")){
						 		status = "Won";
						 	}
						 	else if(winning.equals("0")){
						 		status = "Lost";
						 	}
				 		}
				 		else /*if(ownBases[i].compareTo(def_id) == 0)*/{
				 			 status = "";
						 	if(winning.equals("0")){
						 		status = "Won";
						 	}
						 	else if(winning.equals("1")){
						 		status = "Lost";
						 	}
				 		}
				 		//else {status = "Onbekend";}
				 	}
				 	
				 	/*
				 	
				 	if(winning.equals("1")){
				 		status = "Won";
				 	}
				 	else if(winning.equals("0")){
				 		status = "Lost";
				 	}
				 	*/
				 	
					map = new HashMap<String,String>();
					getBaseName(atk_id);
						String inputText = lastBaseName + " vs ";
						getBaseName(def_id);
						inputText += lastBaseName;
						
						map.put("bases", inputText);
						map.put("status", status+" - "+tijd);
						mylist.add(map);
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			 
			}


			SimpleAdapter adapterSpreekwoorden = new SimpleAdapter(this, mylist, R.layout.attacklogrowview, new String[] {"bases", "status"}, new int[] {R.id.rowListBases,R.id.rowListStatus});
			
			lv.setAdapter(adapterSpreekwoorden);
			

//			lv.setOnItemClickListener(new ListView.OnItemClickListener() {
//			    @Override
//			    public void onItemClick(AdapterView<?> a, View v, int i, long l) {
//			    	JSONObject user = null;
//			    	try {
//						user = results.getJSONObject(i);
//						
////						String naam = user.getString("firstname") + " " + user.getString("suffix") + " " + user.getString("lastname");
////				    	String username = user.getString("username");
////				    	String credits = user.getString("credits");
////				    	String email = user.getString("email");
//				        final Dialog dialog = new Dialog(AttackLogActivity.this);
//			    		 
//			    		 WindowManager.LayoutParams lp = dialog.getWindow().getAttributes();  
//			    		 lp.dimAmount=0.0f;  
//			    		 dialog.getWindow().setAttributes(lp);  
//			    		 dialog.getWindow().addFlags(WindowManager.LayoutParams.FLAG_BLUR_BEHIND);
//			    		 
////			    		 TextView tv = new TextView(dialog.getContext());
////			    		 tv.setPadding(10, 10, 10, 10);
////			    		 tv.setText("Naam:          " + naam + "\n" + 
////			    				    "Email:          " + email+ "\n" +
////			    				    "Username:  " + username + "\n" +
////			    				    "Credits:       " + credits );
//			    		 			
//			    		 dialog.setTitle("User information.");
////			    		 dialog.setContentView(tv);
//			    		 //dialog.setContentView(android.);
//			    		 
//					     
//					    dialog.show();
//						
//					} catch (JSONException e) {
//						// TODO Auto-generated catch block
//						e.printStackTrace();
//					}
//			    }
//			});
	}
	
	
	private void getAttackLogs() {
		Handler handler = new Handler() {
			
			public void handleMessage(Message message) {
				switch (message.what) {
				case HttpConnection.DID_START: {
					break;
				}
				case HttpConnection.DID_SUCCEED: {
					String response = (String) message.obj;
					try {
						JSONObject ranking = new JSONObject(response);
						boolean b = ranking.getBoolean("success");
						if(b){
							results = ranking.getJSONArray("result");
							
							setListViewAdapter();
						
				 		}else{
				 			//geen basisen
						}
					}
					catch (JSONException e) {
						e.printStackTrace();
					}
					break;
				}
				case HttpConnection.DID_ERROR: {
					Exception e = (Exception) message.obj;
					e.printStackTrace();
					break;
				}
				}
			}
			
		};
		new HttpConnection(handler)
				.get("http://frankkie.nl/basewars/api/v4/raw/SELECT%20*%20FROM%20%60CombatLog%60%20WHERE%20(%60attacking_base_id%60%20IN%20(SELECT%20%60id%60%20FROM%20%60Base%60%20WHERE%20player_id%20=%20'13'))%20OR%20(%60defending_base_id%60%20IN%20(SELECT%20%60id%60%20FROM%20%60Base%60%20WHERE%20player_id%20=%20'13'))");
	}
	
	
	private void getOwnBases() {
		Handler handler = new Handler() {
			
			public void handleMessage(Message message) {
				switch (message.what) {
				case HttpConnection.DID_START: {
					break;
				}
				case HttpConnection.DID_SUCCEED: {
					String response = (String) message.obj;
					try {
						JSONObject ranking = new JSONObject(response);
						boolean b = ranking.getBoolean("success");
						if(b){
							ownBasesresult = ranking.getJSONArray("result");
							
							ownBases = new String[ownBasesresult.length()];
							
							for(int i=0; i < ownBasesresult.length(); i++){
								JSONObject o;
								try {
									o = ownBasesresult.getJSONObject(i);
									
									String id =  o.getString("id");
								 	String name = o.getString("name");
								 	String description = o.getString("description");
								 	ownBases[i] = id;
								 	
								} catch (JSONException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}
							}
						
				 		}else{
				 			//geen basissen
						}
					}
					catch (JSONException e) {
						e.printStackTrace();
					}
					break;
				}
				case HttpConnection.DID_ERROR: {
					Exception e = (Exception) message.obj;
					e.printStackTrace();
					break;
				}
				}
			}
			
		};
		new HttpConnection(handler)
			.get("http://frankkie.nl/basewars/api/v4/bases/user/13");
	}
	
	
	
	private void getBaseName(String atk_id) {

		Handler handler = new Handler() {
			
			public void handleMessage(Message message) {
				switch (message.what) {
				case HttpConnection.DID_START: {
					break;
				}
				case HttpConnection.DID_SUCCEED: {
					String response = (String) message.obj;
					try {
						JSONObject ranking = new JSONObject(response);
						boolean b = ranking.getBoolean("success");
						if(b){
							Baseresult = ranking.getJSONArray("result");
							
							
							for(int i=0;i < Baseresult.length();i++){
								JSONObject o;
								try {
									o = Baseresult.getJSONObject(i);
									
								
									lastBaseName = o.getString("name");
								 	
								 	//return name;
								 	
								} catch (JSONException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}
							}
						
				 		}else{
				 			//geen basisen
						}
					}
					catch (JSONException e) {
						e.printStackTrace();
					}
					break;
				}
				case HttpConnection.DID_ERROR: {
					Exception e = (Exception) message.obj;
					e.printStackTrace();
					break;
				}
				}
			}
			
		};
		new HttpConnection(handler)
			.get("http://frankkie.nl/basewars/api/v4/raw/SELECT%20%60name%60%20FROM%20%60Base%60%20WHERE%20%60id%60%20=%20'"+atk_id+"'");
		
	}
	
	
	
}



